package cn.edu.scau.dormitory_management_system.controller;

import cn.edu.scau.dormitory_management_system.entity.SysLogEntity;
import cn.edu.scau.dormitory_management_system.service.SysLogService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author djc
 * @date 2021/8/4
 * @time 18:55
 */
@RestController
@RequestMapping("/admin/system/log")
public class SysLogController {
    @Autowired
    private SysLogService logService;

    @GetMapping("/list")
    public Object getLog(@RequestParam(defaultValue = "1") int current,
                         int size) {
        JSONObject object = new JSONObject();

        IPage<SysLogEntity> page = new Page<>(current, size);
        QueryWrapper<SysLogEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("log_id");
        page = logService.page(page, wrapper);

        if(page.getRecords().isEmpty()) {
            object.put("code", 0);
            object.put("msg", "无登录数据");
        }else {
            object.put("code", 200);
            object.put("page", page);
        }

        return object;
    }

    @GetMapping("/query")
    public Object getLog(@RequestParam(defaultValue = "1") int current,
                         int size,
                         String userName) {
        JSONObject object = new JSONObject();

        IPage<SysLogEntity> page = new Page<>(current, size);
        QueryWrapper<SysLogEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("log_id");
        wrapper.like("user_name", userName);
        page = logService.page(page, wrapper);

        if(page.getRecords().isEmpty()) {
            object.put("code", 0);
            object.put("msg", "无数据");
        }else {
            object.put("code", 200);
            object.put("page", page);
        }

        return object;
    }

    @PostMapping("/delete")
    public Object deleteLog(int id) {
        JSONObject object = new JSONObject();
        boolean b = logService.removeById(id);

        if(b) {
            object.put("code", 200);
        }else {
            object.put("code", 0);
        }

        return object;
    }

    @PostMapping("/deletes")
    public Object deleteLogs(@RequestBody List<Integer> ids) {
        JSONObject object = new JSONObject();
        boolean b = logService.removeByIds(ids);

        if(b) {
            object.put("code", 200);
        }else {
            object.put("code", 0);
        }

        return object;
    }
}
